
#import "IHttp.h"

#import "GZip.h"



@implementation IHttp

-(void)free
{
	[buf release];
	if (connection!=nil) {
		[connection release];
	}
}

-(void)cancel
{
	[connection cancel];
	if(timer!=nil && [timer isValid])
	{
		[timer invalidate];
		timer = nil;
	}
}

-(void)getData:(HTTP_TOOLS*)p
{
	pHttp = p;
	//printf("\n url len:%d",strlen(pHttp->pUrl));
	buf = [[NSMutableData alloc] initWithLength:0];
	NSURL *url=[NSURL URLWithString:[NSString stringWithUTF8String:pHttp->pUrl]];
	
	NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:url];// cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
	
	NSString *msgLegth=[NSString stringWithFormat:@"%d", pHttp->nSendLen];
	
	[theRequest addValue:[NSString stringWithUTF8String:pHttp->pContentType] forHTTPHeaderField:@"Content-Type"];
	
	
	[theRequest addValue:msgLegth forHTTPHeaderField:@"Content-Length"];
	if (pHttp->nSendLen>0) {
		[theRequest setHTTPMethod:@"POST"];
		NSData *sender = [NSData dataWithBytes:pHttp->pSendData length:(NSUInteger)pHttp->nSendLen];
		[theRequest setHTTPBody:sender];
	}
	else 
	{
		[theRequest setHTTPMethod:@"GET"];
	}
	
	timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(timeOut:) userInfo:nil repeats:NO]; 
	connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

}




//收到响应时, 会触发
- (void)connection:(NSURLConnection *)aConn didReceiveResponse:(NSURLResponse *)aResponse
{
//	// 你可以在里面判断返回结果, 或者处理返回的http头中的信息
//	//显示所有头信息
//	NSDictionary *pDic = [aResponse allHeaderFields];
//	NSArray *pKey;
//	NSArray *pVal;
//	pKey = [pDic allKeys];
//	pVal = [pDic allValues];
//	char sBuf[1024];
//	memset(sBuf, 0, sizeof(sBuf));
//	strcpy(sBuf, "\n\nhttp head start\n");
//	for (int i=0; i<pKey.count; i++) {
//		strcat(sBuf, [(NSString*)[pKey objectAtIndex:i] cString]);
//		strcat(sBuf, ": ");
//		strcat(sBuf, [(NSString*)[pVal objectAtIndex:i] cString]);
//		strcat(sBuf, "\n");
//	}
//	strcat(sBuf, "http head end\n\n");
//	printf("%s",sBuf);
  
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)aResponse;
  printf("\nIHTTP status code:%d",[httpResponse statusCode]);
  if ((([httpResponse statusCode]/100) == 2)) {
    
  }
  else
  {
    //statusCode>300，抛出网络错误
    //网络错误，结束定时器
    if(timer!=nil && [timer isValid])
    {
      [timer invalidate];
      timer = nil;
    }
    //取消请求
    [self cancel];
    HttpTools_ResedData(pHttp, HTTP_STATE_NET_ERROR);
  }
}


// 每收到一次数据, 会调用一次
- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data
{
	// 因此一般来说,是	
    [buf appendData:data];
}

// 超时调用
-(void)timeOut:(NSTimer*)t
{
	//取消请求
	[self cancel];
	HttpTools_ResedData(pHttp, HTTP_STATE_TIME_OUT);

}

// 网络错误时触发
- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error
{
	//网络错误，结束定时器
	if(timer!=nil && [timer isValid])
	{
		[timer invalidate];
		timer = nil;
	}
	//取消请求
	[self cancel];
	HttpTools_ResedData(pHttp, HTTP_STATE_NET_ERROR);

}

// 全部数据接收完毕时触发
- (void)connectionDidFinishLoading:(NSURLConnection *)aConn
{
	//请求数据成功，结束定时器
	if(timer!=nil && [timer isValid])
	{
		[timer invalidate];
		timer = nil;
	}
	
	pHttp->nRecvDataLen = buf.length;
	void *pBuf = Tools_Malloc(pHttp->nRecvDataLen+2);
	[buf getBytes:pBuf length:pHttp->nRecvDataLen];
	
	//解压GZIP数据
	int nUnGZipLen = GZIP_Len(pBuf, pHttp->nRecvDataLen);
	if (nUnGZipLen>0) {
		pHttp->pRecvData = Tools_Malloc(nUnGZipLen+2);
		GZIP_inflate(pBuf, pHttp->nRecvDataLen, pHttp->pRecvData);
		pHttp->nRecvDataLen = nUnGZipLen;
		Tools_Free(&pBuf);
	}
	else
	{
		pHttp->pRecvData = pBuf;
	}

    
	HttpTools_ResedData(pHttp, HTTP_STATE_FINISH);
}

@end
